import { type FC, cloneElement } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { useMemoizedFn } from 'ahooks';
import { hexToRgba } from '@/utils/helper';
import { useDatas } from './hooks';
import { primaryColor } from '@/constants/Colors';
import { type MenuItemProps } from './types';
import styles from './styles';

const iconSize = 20;
const themeColor = hexToRgba(primaryColor, .9);
const defaultIconBgColor = hexToRgba(primaryColor, .1);

const MenuItem: FC<MenuItemProps> = (props) => {
  const {
    icon,
    title,
    onPress,
    iconColor = themeColor,
    iconBgColor = defaultIconBgColor,
  } = props;

  const { onClose } = useDatas();

  const iconAttrs = {
    size: iconSize,
    color: iconColor
  }

  const iconStyles = [
    styles.itemIcon,
    { backgroundColor: iconBgColor }
  ];

  const handleClick = useMemoizedFn(async () => {
    if (await onPress?.() ?? true) onClose?.();
  });

  return (
    <TouchableOpacity
      style={styles.item}
      activeOpacity={.8}
      onPressIn={handleClick}
    >
      <View style={iconStyles}>
        {cloneElement(icon, iconAttrs)}
      </View>
      <Text style={styles.itemText}>
        {title}
      </Text>
    </TouchableOpacity>
  );
}

export default MenuItem;